﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PFMConfigurations;
using System.IO;
using PFMCandidate;

namespace PFMFinders
{
   public  class PFMFileFinder:PFMFinder
    {
        List<String> sFiles = null;
		int iIndex = 0;

		public PFMFileFinder()
		{
            //sFiles = new List<string>();
		}

        public PFMFileFinder(Target aTarget)
            : base(aTarget)
		{
            sFiles = new List<string>();
            if (aTarget.Subdirectory) 
			  GetAllDirectoryFiles();
			else
                sFiles.AddRange(Directory.GetFiles(aTarget.Location,  aTarget.Filter));
		}

		public override Candidate FindNext()
		{
			Candidate Result = null;

			if (iIndex < sFiles.Count)
			{
				Result = CreateFileCandidate(sFiles[iIndex]);
				iIndex++;
			}

			return Result;
		}

		public void Reset()
		{
			this.iIndex = 0;
		}

		protected Candidate CreateFileCandidate(string sFileName)
		{
		    FileInfo aFI;
			Candidate Result = null;
			if (File.Exists(sFileName)) 
			{
				aFI = new FileInfo(sFileName);
				Result =CandidateFactory.CreateCandidate(o_Target, sFileName, aFI.CreationTime, aFI.Length);
			}	
			return Result;
		}

		protected void GetSubDirectoryFiles(string sSubDirec, string sExt)
		{
			string[] sDirecs = null;
			//string[] sSubfiles = null;
			string sDirectory = "";

			//string[] Result = Directory.GetFiles(sSubDirec, this.o_Target.Filter);
            this.sFiles.AddRange(Directory.GetFiles(sSubDirec, this.o_Target.Filter));
            sDirecs = Directory.GetDirectories(sSubDirec);

			for (int iCount = 0; iCount < sDirecs.Length;  iCount++)
			{
				sDirectory = sDirecs[iCount];
				GetSubDirectoryFiles(sDirectory, sExt);
               
			}

			
		}

		protected void   GetAllDirectoryFiles()
		{
              GetSubDirectoryFiles(o_Target.Location,o_Target.Filter);
		}

		protected void AppendFiles(string[] Source)
		{
            //int iDelta = Dest.Length - Source.Length;
            sFiles.AddRange(Source);
            //for (int iCount = 0; iCount < Source.Length; iCount++) 
            //    Dest[iDelta + iCount] = Source[iCount];
            
		}

        //protected string[] SetLength(string[] Source, int iNewLength)
        //{
        //    string[] newArray = new string[iNewLength];
        //    Source.CopyTo(newArray, 0);
        //    return newArray;
        //}

		public override int GetCount()
		{
			return sFiles.Count;
		}

		public override Candidate GetItem(int iIndex)
		{
			Candidate Result = null;

			if (iIndex < sFiles.Count) 
				Result = CreateFileCandidate(sFiles[iIndex]);
			
			return Result;
		}

		public PFMFileFinderEnumerator GetEnumerator()
		{
            return new PFMFileFinderEnumerator(this);
		}


    }
}
